package com.koomii.myproject.common;

import java.util.HashMap;

import net.sf.json.JSONObject;

import com.koomii.common.util.UrlUtils;
import com.koomii.myproject.enumeration.BizCode;

/**
 * API接口通信BEAN
 * @author david
 *
 */
public class MessageBean extends HashMap<String, Object> {

	private static final long serialVersionUID = 1L;

	public static final String KEY_CODE = "code";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_TOKEN = "token";
	
	public String toEncodeString() {
		return UrlUtils.urlEncode(JSONObject.fromObject(this).toString());
	}
	
	public MessageBean() {
		this.fireSuccess();
	}
	
	/**
	 * 业务状态码
	 * @param code 业务代码
	 */
	public void setCode(String code) {
		super.put(KEY_CODE, code);
	}
	
	/**
	 * 业务反馈消息
	 * @param message 业务消息
	 */
	public void setMessage(String message) {
		super.put(KEY_MESSAGE, message);
	}
	
	/**
	 * 设置报文接口状态码
	 * 这样可省去分别设置setCode() setMessage()
	 * @param apiCode
	 */
	public void setApiCode(BizCode apiCode) {
		super.put(KEY_CODE, apiCode.getCode());
		super.put(KEY_MESSAGE,apiCode.getText());
	}
	
	/**
	 * 激活为成功
	 */
	public void fireSuccess() {
		super.put("status", 1);
	}
	
	/**
	 * 激活为失败
	 */
	public void fireFailed() {
		super.put("status", 0);
	}
	
	/**
	 * 是否成功
	 * @return
	 */
	public boolean isSuccess() {
		Object status = get("status");
		if(status!=null && "1".equals(status.toString())) {
			return true;
		} else {
			return false;
		}
	}
	
	
	/**
	 * 添加数据项
	 * @param key
	 * @param value
	 */
	public void addDataItem(String key,Object value) {
		super.put(key, value);
	}
	
	public static void main(String[] args) {
		MessageBean msg = new MessageBean();
		msg.setApiCode(BizCode.ACCOUNT_MONEY_LOW);
		System.out.println(UrlUtils.urlEncode(msg.toEncodeString()));
		System.out.println(UrlUtils.urlDecode(msg.toEncodeString()));
	}

}
